package com.gx.city_picker.adpater;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.gx.city_picker.OnItemClickListener;
import com.gx.city_picker.R;
import com.gx.city_picker.entity.ProvinceEntity;
import java.util.ArrayList;
import java.util.List;

/**
 * 省 适配器
 * <p>
 * Created by Guoxin on 2021-07-05
 */
public class ProvincesAdapter extends RecyclerView.Adapter<ProvincesAdapter.ViewHolder> {

    private Context              mContext;
    private OnItemClickListener  listener;
    private List<ProvinceEntity> mDatas = new ArrayList<>();
    private ProvinceEntity       mSelector;
    private int                  mSelectColor;
    private int                  mDefaultColor;

    public ProvincesAdapter(Context context, int selectColor, int defaultColor) {
        this.mContext = context;
        this.mSelectColor = selectColor;
        this.mDefaultColor = defaultColor;
    }

    public void setListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public void setDatas(List<ProvinceEntity> datas) {
        this.mDatas = datas;
        this.notifyDataSetChanged();
    }

    public void setSelector(ProvinceEntity data) {
        this.mSelector = data;
        this.notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_city_picker, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ProvinceEntity data = mDatas.get(position);
        holder.textView.setText(data.getProvinceName());
        if (null != mSelector && data.getProvinceId() == mSelector.getProvinceId()) {
            holder.textView.setTextColor(mContext.getColor(mSelectColor));
            holder.imageView.setVisibility(View.VISIBLE);
        }
        else {
            holder.textView.setTextColor(mContext.getColor(mDefaultColor));
            holder.imageView.setVisibility(View.GONE);
        }
        holder.itemView.setOnClickListener(v -> {
            listener.onItemClickListener(position, data);
            mSelector = data;
            notifyDataSetChanged();
        });
    }

    @Override
    public int getItemCount() {
        return null == mDatas ? 0 : mDatas.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        TextView  textView;
        ImageView imageView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.textview);
            imageView = itemView.findViewById(R.id.imageview);
        }
    }
}
